package org.fast.cms.controller.admin;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.fast.cms.common.core.AbstractController;
import org.fast.cms.common.domain.response.JsonResponse;
import org.fast.cms.common.utils.string.StringUtils;
import org.fast.cms.domain.admin.response.user.User;
import org.fast.cms.security.MyFormAuthenticationFilter;
import org.fast.cms.utils.UserUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/** 
* @author weigen.ye 
* @date 创建时间：2017年6月18日 上午7:29:35 
*
*/
@Controller
@RequestMapping(value="/admin")
public class LoginController extends AbstractController{

    @RequestMapping(value="/login", method= RequestMethod.GET)
    public String loginView() {
    	//已登录重定到管理后台首页
    	if (UserUtils.getLoginUserInfo() != null) {
    		return getRedirectTemplate("index",true,false);
    	}
    	return getAdminTemplate("login");
    }

    @ResponseBody
    @RequestMapping(value="/loginCheck", method= RequestMethod.POST)
    public JsonResponse<User> loginCheck(HttpServletRequest req, HttpServletResponse resp) {
    	
    	if (UserUtils.getLoginUserInfo() != null) {
    		Cookie[] cs = req.getCookies();
    		for (Cookie c : cs) {
    			if ("fast.cms.sessionid".equals(c.getName())) {
    				resp.addCookie(c);
    			}
    		}
    		return success( UserUtils.getUser(), "已登录");
    	}
    	
    	String message = (String)req.getAttribute(MyFormAuthenticationFilter.DEFAULT_MESSAGE_PARAM);
    	if (StringUtils.isBlank(message)) {
    		message = "用户或密码错误, 请重试.";
    	}
    	return error(message);
    }

    @RequiresUser
    @ResponseBody
    @RequestMapping(value="/loginUser/info", method= RequestMethod.GET)
    public JsonResponse<User> getLoginUserInfo(HttpServletRequest req) {
    	return success( UserUtils.getUser());
    }

    @RequestMapping(value="/logout", method= RequestMethod.GET)
    public String logout() {
    	UserUtils.clearSession();
    	SecurityUtils.getSubject().logout();
    	return getRedirectTemplate("login",true,false);
    }
}